package com.linq.cool.beauty.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.linq.cool.beauty.domain.BeautyVehicle;
import com.linq.cool.beauty.dto.BeautyVehicleQueryDTO;
import com.linq.cool.beauty.mapper.BeautyVehicleMapper;
import com.linq.cool.beauty.service.BeautyVehicleService;
import com.linq.cool.beauty.vo.BeautyVehicleVO;
import com.linq.cool.common.core.exception.BusinessException;
import com.linq.cool.common.core.utils.SecurityUtils;
import org.springframework.stereotype.Service;

import java.util.Date;

/**
 * @Author: yqlin
 * @Date: 2021/2/1 03:59
 * @Description:
 * @Version: 1.0.0
 */

@Service
public class BeautyVehicleServiceImpl extends ServiceImpl<BeautyVehicleMapper, BeautyVehicle> implements BeautyVehicleService {

    @Override
    public IPage<BeautyVehicleVO> listByPage(IPage<BeautyVehicleVO> page, BeautyVehicleQueryDTO dto) {
        return baseMapper.listByPage(page, dto);
    }

    @Override
    public boolean saveVehicle(BeautyVehicle vehicle) {
        // 车牌号唯一
        if (this.checkLicenseNumberUnique(vehicle)) {
            throw new BusinessException("新增车辆'" + vehicle.getLicenseNumber() + "'失败，车牌号已存在");
        }
        vehicle.setCreator(SecurityUtils.getUserId());
        return this.save(vehicle);
    }

    @Override
    public boolean updateVehicle(BeautyVehicle vehicle) {
        // 车牌号唯一
        if (this.checkLicenseNumberUnique(vehicle)) {
            throw new BusinessException("修改车辆'" + vehicle.getLicenseNumber() + "'失败，车牌号已存在");
        }
        vehicle.setModifier(SecurityUtils.getUserId()).setGmtModified(new Date());
        return this.updateById(vehicle);
    }

    /**
     * 车牌号唯一
     *
     * @param vehicle
     *
     * @return
     */
    private boolean checkLicenseNumberUnique(BeautyVehicle vehicle) {
        Long vehicleId = null == vehicle.getId() ? -1L : vehicle.getId();
        BeautyVehicle one = this.getOne(new LambdaQueryWrapper<BeautyVehicle>()
                                                .select(BeautyVehicle::getId, BeautyVehicle::getLicenseNumber)
                                                .eq(BeautyVehicle::getLicenseNumber, vehicle.getLicenseNumber())
        );
        // 判断id是否一致 不一致就代表 唯一 false
        return null != one && !vehicleId.equals(one.getId());
    }
}
